/*
 * $Id: MailTextGenerator.java,v 1.5 2010/05/10 19:47:07 navdeep_mahajan Exp $
 *
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 *
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package com.ge.healthcare.autosc.common.util.mail.support;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;

import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.database.dao.ICodeDetailsDAO;
import com.ge.healthcare.autosc.common.database.dao.IFileTransferDetailsDAO;
import com.ge.healthcare.autosc.common.database.dao.IRequestDefnDAO;
import com.ge.healthcare.autosc.common.database.dao.IRequestPropertiesDAO;
import com.ge.healthcare.autosc.common.database.dao.IRequestTypeDAO;
import com.ge.healthcare.autosc.common.database.dao.ITaskCategoryInfoDAO;
import com.ge.healthcare.autosc.common.database.pojo.AbstractFileTransferDetails;
import com.ge.healthcare.autosc.common.database.pojo.AbstractRequest;
import com.ge.healthcare.autosc.common.database.pojo.AbstractTask;
import com.ge.healthcare.autosc.common.database.pojo.ActFileTransferDetails;
import com.ge.healthcare.autosc.common.database.pojo.ActRequest;
import com.ge.healthcare.autosc.common.database.pojo.ActRequestProperties;
import com.ge.healthcare.autosc.common.database.pojo.CfgCodeDetails;
import com.ge.healthcare.autosc.common.database.pojo.CfgRequestDefn;
import com.ge.healthcare.autosc.common.database.pojo.CfgRequestType;
import com.ge.healthcare.autosc.common.database.pojo.CfgTaskCategoryInfo;
import com.ge.healthcare.autosc.common.util.ASCFileHandler;
import com.ge.healthcare.autosc.common.util.ApplicationInfo;
import com.ge.healthcare.autosc.common.util.PropertyConstants;
import com.ge.healthcare.autosc.common.util.TimeFormatStandard;
import com.ge.healthcare.autosc.common.util.mail.MailConstants;

/**
 * This object generates a notify message based on the template files that are
 * passed into the system
 * 
 * @author 212028693
 * 
 */
public class MailTextGenerator {
	public static final String REPORT_SEPERATOR = "\n\n";
	protected String msgTmplFile = null;
	protected String msgTmpl = null;
	protected String taskTmplFile = null;

	protected String taskTmpl = null;
	protected String fileTmplFile = null;
	protected String fileTmpl = null;
	protected String subjectTmpl;

	private ICodeDetailsDAO codeDAO;
	private ITaskCategoryInfoDAO taskCategoryDAO;
	private IRequestTypeDAO requestTypeDAO;
	private IRequestDefnDAO requestDefnDAO;
	private IRequestPropertiesDAO rPropDAO;
	private IFileTransferDetailsDAO fileDAO;

	/**
	 * Without the template files there is no way the p
	 * 
	 * @param msgTemplateFile
	 * @param taskTemplateFile
	 * @param fileTemplateFile
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public MailTextGenerator(String subjectTemplate, String msgTemplateFile,
			String taskTemplateFile, String fileTemplateFile) throws Exception {

		this.subjectTmpl = stripWhiteSpace(subjectTemplate);
		this.msgTmplFile = stripWhiteSpace(msgTemplateFile);
		this.taskTmplFile = stripWhiteSpace(taskTemplateFile);
		this.fileTmplFile = stripWhiteSpace(fileTemplateFile);

		this.msgTmpl = ASCFileHandler.readFileAsString(this.msgTmplFile);
		this.taskTmpl = ASCFileHandler.readFileAsString(this.taskTmplFile);
		this.fileTmpl = ASCFileHandler.readFileAsString(this.fileTmplFile);
	}

	public String generate(AbstractRequest request, List<AbstractTask> tasks) {
		String txt = new String(this.msgTmpl);
		if (!ASCUtil.isNullOrEmptyList(tasks)) {
			txt = replaceAll(txt, MailConstants.MSG_TASK, tasks.get(0)
					.getTaskType());
		} else {
			txt = replaceAll(txt, MailConstants.MSG_TASK, "Unknown");
		}
		String scUrl = ApplicationInfo.getInstance().getProperty(
				PropertyConstants.MAIL_HEADER_COMMENT_TO);
		txt = replaceAll(txt, MailConstants.MSG_COMMENT_TO, scUrl);
		txt = getRequestStatusText(txt, request);

		String taskMsg = "";
		for (AbstractTask task : tasks) {
			taskMsg += getTaskStatusText(task) + REPORT_SEPERATOR;
		}
		txt = replaceAll(txt, MailConstants.MSG_TASK_RESULT_DATA, taskMsg);

		List<ActFileTransferDetails> files = fileDAO
				.getExternalFileTransferLstByRequestId(request.getRequestId());
		String fileMsg = "";
		if (!ASCUtil.isNullOrEmptyList(files)) {
			for (ActFileTransferDetails file : files) {
				if (IFileTransferDetailsDAO.UPLOAD_FROM_DEVICE
						.equalsIgnoreCase(file.getDirection())) {
					fileMsg += getFileStatusText(file) + REPORT_SEPERATOR;
				}
			}
		}
		txt = replaceAll(txt, MailConstants.MSG_FILE_TRANSFER_SUMMARY, fileMsg);
		return txt;
	}

	public String generateSubject(ActRequest request) {
		String txt = subjectTmpl;
		txt = txt.replaceAll(MailConstants.SUBJECT_SYSTEM_ID, request
				.getSystemId());
		return txt;
	}

	/**
	 * This will return txt with all the request values replaced
	 * 
	 * @return
	 */
	protected String getRequestStatusText(String requestTmplString,
			AbstractRequest request) {
		String txt = requestTmplString;
		txt = replaceAll(txt, MailConstants.MSG_REQUEST_LIST_ID, request
				.getRequestListId().toString());
		txt = replaceAll(txt, MailConstants.MSG_REQUEST_ID, request
				.getRequestId().toString());
		txt = replaceAll(txt, MailConstants.MSG_SYSTEM_ID, request
				.getSystemId());
		txt = replaceAll(txt, MailConstants.MSG_USN, request.getUsn());
		txt = replaceAll(txt, MailConstants.MSG_MLN, request.getMln());
		txt = replaceAll(txt, MailConstants.MSG_MODALITY, request.getModality());
		txt = replaceAll(txt, MailConstants.MSG_PRODUCT_LINE, request
				.getProductLine());
		txt = replaceAll(txt, MailConstants.MSG_DATE, TimeFormatStandard
				.getDtInEndUserDisplayFormat(request.getStartTime()));

		CfgRequestType type = requestTypeDAO
				.getRequestTypeByRequestListId(request.getRequestListId());
		if (!ASCUtil.isNullOrEmptyObject(type)) {
			txt = replaceAll(txt, MailConstants.MSG_REQUEST_TYPE_NAME, type
					.getRequestTypeName());
		} else {
			txt = replaceAll(txt, MailConstants.MSG_REQUEST_TYPE_NAME,
					MailConstants.NOT_FOUND);
		}
		CfgRequestDefn defn = null;
		if (!ASCUtil.isNullOrEmptyObject(request.getRequestDefnId())) {
			defn = requestDefnDAO
					.getByRequestDefnId(request.getRequestDefnId());
		}
		if (!ASCUtil.isNullOrEmptyObject(defn)) {
			txt = replaceAll(txt, MailConstants.MSG_REQUEST_DESC, defn
					.getRequestDesc());
		} else {
			txt = replaceAll(txt, MailConstants.MSG_REQUEST_TYPE_NAME,
					MailConstants.NOT_FOUND);
		}

		return txt;
	}

	/**
	 * Return the Status test for a single file
	 * 
	 * @param file
	 * @return
	 */
	protected String getFileStatusText(AbstractFileTransferDetails file) {
		String txt = new String(this.fileTmpl);
		txt = replaceAll(txt, MailConstants.FILE_NAME, file.getFileName());
		txt = replaceAll(txt, MailConstants.FILE_SIZE, file.getContentSize()
				.toString());
		txt = replaceAll(txt, MailConstants.FILE_STATUS, file.getStatus());
		return txt;
	}

	/**
	 * Return the Status text for a single task.
	 * 
	 * @param task
	 * @return
	 */
	protected String getTaskStatusText(AbstractTask task) {
		String txt = new String(this.taskTmpl);
		txt = replaceAll(txt, MailConstants.TASK_NAME, task.getTaskType());
		// Task Category
		CfgTaskCategoryInfo category = null;
		category = taskCategoryDAO.getTaskCategoryForTaskType(task
				.getTaskType());
		if (!ASCUtil.isNullOrEmptyObject(category)) {
			txt = replaceAll(txt, MailConstants.TASK_CATEGORY, category
					.getTaskCategory());
		} else {
			txt = replaceAll(txt, MailConstants.TASK_CATEGORY,
					MailConstants.NOT_FOUND);
		}
		// Code Details
		if (!ASCUtil.isNullOrEmptyObject(task.getCodeId())) {
			CfgCodeDetails code = codeDAO.getCodeDetailsByID(task.getCodeId());
			txt = replaceAll(txt, MailConstants.TASK_STATUS_CODE, code
					.getCodeGroupLong());
			ActRequestProperties rCodeProp = rPropDAO
					.getRequestPropertiesByRequestIdAndName(
							task.getRequestId(),
							PropertyConstants.TASK_ACTUAL_FAILURE_CODE
									+ task.getTaskId());
			if (!ASCUtil.isNullOrEmptyObject(rCodeProp)) {
				String codeId = rCodeProp.getPropertyValue();
				if (!ASCUtil.isNullOrEmpty(codeId)) {
					code = codeDAO.getCodeDetailsByID(Long.parseLong(codeId
							.trim()));
				}
			}
			txt = replaceAll(txt, MailConstants.TASK_CODE, code.getCodeName());
			txt = replaceAll(txt, MailConstants.TASK_CODE_DESC, code
					.getCodeDesc());
		} else {
			txt = replaceAll(txt, MailConstants.TASK_STATUS_CODE,
					MailConstants.NOT_FOUND);
			txt = replaceAll(txt, MailConstants.TASK_CODE,
					MailConstants.NOT_FOUND);
			txt = replaceAll(txt, MailConstants.TASK_CODE_DESC,
					MailConstants.NOT_FOUND);
		}
		return txt;
	}

	private String replaceAll(String txt, String regex, String replacement) {
		if (ASCUtil.isNullOrEmpty(replacement)) {
			txt = txt.replaceAll(regex, "");
		} else {
			txt = txt.replaceAll(regex, replacement);
		}
		return txt;
	}

	private String stripWhiteSpace(String txt) throws RESyntaxException {
		RE stripWhiteSpace = new RE("^\\s*(.*)\\s*$");
		if (stripWhiteSpace.match(txt)) {
			txt = stripWhiteSpace.getParen(1);
		}
		return txt;
	}

	/**
	 * @param codeDAO
	 *            the codeDAO to set
	 */
	public void setCodeDAO(ICodeDetailsDAO codeDAO) {
		this.codeDAO = codeDAO;
	}

	/**
	 * @param taskCategoryDAO
	 *            the taskCategoryDAO to set
	 */
	public void setTaskCategoryDAO(ITaskCategoryInfoDAO taskCategoryDAO) {
		this.taskCategoryDAO = taskCategoryDAO;
	}

	/**
	 * @param requestTypeDAO
	 *            the requestTypeDAO to set
	 */
	public void setRequestTypeDAO(IRequestTypeDAO requestTypeDAO) {
		this.requestTypeDAO = requestTypeDAO;
	}

	/**
	 * @param requestDefnDAO
	 *            the requestDefnDAO to set
	 */
	public void setRequestDefnDAO(IRequestDefnDAO requestDefnDAO) {
		this.requestDefnDAO = requestDefnDAO;
	}

	/**
	 * @param fileDAO
	 *            the fileDAO to set
	 */
	public void setFileDAO(IFileTransferDetailsDAO fileDAO) {
		this.fileDAO = fileDAO;
	}

	/**
	 * @param rPropDAO
	 *            the rPropDAO to set
	 */
	public void setrPropDAO(IRequestPropertiesDAO rPropDAO) {
		this.rPropDAO = rPropDAO;
	}

}
